// Alfred CI/CD Frontend Application

class AlfredApp {
    constructor() {
        this.apiBase = '/api/v1';
        this.flows = [];
        this.executions = [];
        this.currentFlowId = null;
        this.currentFlowNodes = [];
        this.currentNodeId = null;
        this.currentNodeActions = [];
        this.init();
    }

    init() {
        this.loadFlows();
        this.loadExecutions();
        this.setupEventListeners();
        this.updateButlerMessage('Alfred 已准备就绪，随时为您服务！');
        
        // Auto refresh every 30 seconds
        setInterval(() => {
            this.loadFlows();
            this.loadExecutions();
        }, 30000);
    }

    setupEventListeners() {
        // Flow form submission
        const flowForm = document.getElementById('flow-form');
        if (flowForm) {
            flowForm.addEventListener('submit', (e) => {
                e.preventDefault();
                this.handleFlowSubmission();
            });
        }

        // Node form submission
        const nodeForm = document.getElementById('node-form');
        if (nodeForm) {
            nodeForm.addEventListener('submit', (e) => {
                e.preventDefault();
                this.handleNodeSubmission();
            });
        }

        // Close modal when clicking outside
        const modal = document.getElementById('flow-modal');
        if (modal) {
            modal.addEventListener('click', (e) => {
                if (e.target === modal) {
                    this.closeModal();
                }
            });
        }

        const nodeModal = document.getElementById('node-modal');
        if (nodeModal) {
            nodeModal.addEventListener('click', (e) => {
                if (e.target === nodeModal) {
                    closeNodeModal();
                }
            });
        }

        // Escape key to close modal
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') {
                this.closeModal();
                closeNodeModal();
            }
        });
    }

    async apiCall(endpoint, options = {}) {
        try {
            const response = await fetch(`${this.apiBase}${endpoint}`, {
                headers: {
                    'Content-Type': 'application/json',
                    ...options.headers
                },
                ...options
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            return await response.json();
        } catch (error) {
            console.error('API call failed:', error);
            this.updateButlerMessage(`API调用失败: ${error.message}`, 'error');
            throw error;
        }
    }

    async loadFlows() {
        try {
            const response = await this.apiCall('/flows');
            // 处理新的API响应格式：统一的APIResponse结构
            if (response.code === 0 && response.data) {
                this.flows = Array.isArray(response.data) ? response.data : [response.data];
            } else {
                this.flows = [];
                if (response.message) {
                    this.updateButlerMessage(`加载工作流失败: ${response.message}`, 'error');
                }
            }
            this.renderFlows();
        } catch (error) {
            console.error('Failed to load flows:', error);
            this.flows = [];
            this.renderFlows();
        }
    }

    async loadExecutions() {
        try {
            const response = await this.apiCall('/executions');
            // 处理新的API响应格式：统一的APIResponse结构
            if (response.code === 0 && response.data) {
                this.executions = Array.isArray(response.data) ? response.data : [response.data];
            } else {
                this.executions = [];
                if (response.message) {
                    this.updateButlerMessage(`加载执行记录失败: ${response.message}`, 'error');
                }
            }
            this.renderExecutions();
        } catch (error) {
            console.error('Failed to load executions:', error);
            this.executions = [];
            this.renderExecutions();
        }
    }

    renderFlows() {
        const container = document.getElementById('flows-list');
        if (!container) return;

        if (this.flows.length === 0) {
            container.innerHTML = '<div class="loading">暂无工作流</div>';
            return;
        }

        container.innerHTML = this.flows.map(flow => `
            <div class="build-item" onclick="app.showFlowDetails('${flow.id}')">
                <h3>${this.escapeHtml(flow.name)}</h3>
                <p><strong>仓库:</strong> ${this.escapeHtml(flow.repo_url)}</p>
                <p><strong>分支:</strong> ${this.escapeHtml(flow.branch || 'main')}</p>
                ${flow.description ? `<p><strong>描述:</strong> ${this.escapeHtml(flow.description)}</p>` : ''}
                <p><strong>创建时间:</strong> ${this.formatDate(flow.created_at)}</p>
                <div style="margin-top: 10px;">
                    <button class="primary-btn" onclick="event.stopPropagation(); app.executeFlow('${flow.id}')" style="margin-right: 10px;">执行</button>
                    <button class="secondary-btn" onclick="event.stopPropagation(); app.deleteFlow('${flow.id}')">删除</button>
                </div>
            </div>
        `).join('');
    }

    renderExecutions() {
        const container = document.getElementById('executions-list');
        if (!container) return;

        if (this.executions.length === 0) {
            container.innerHTML = '<div class="loading">暂无执行记录</div>';
            return;
        }

        container.innerHTML = this.executions.map(execution => `
            <div class="build-item" onclick="app.showExecutionDetails('${execution.id}')">
                <h3>执行 #${execution.id}</h3>
                <p><strong>工作流:</strong> ${this.escapeHtml(execution.flow_name || 'Unknown')}</p>
                <p><strong>状态:</strong> <span class="build-status status-${execution.status}">${this.getStatusText(execution.status)}</span></p>
                <p><strong>开始时间:</strong> ${this.formatDate(execution.started_at)}</p>
                ${execution.finished_at ? `<p><strong>结束时间:</strong> ${this.formatDate(execution.finished_at)}</p>` : ''}
                ${execution.error ? `<p style="color: var(--accent-color);"><strong>错误:</strong> ${this.escapeHtml(execution.error)}</p>` : ''}
                <div class="execution-details" id="execution-details-${execution.id}" style="display: none;">
                    <div class="execution-progress">
                        <div class="execution-progress-bar ${execution.status === 'failed' ? 'failed' : ''}" style="width: ${this.calculateExecutionProgress(execution)}%"></div>
                    </div>
                    <div class="execution-nodes" id="execution-nodes-${execution.id}">
                        <h4>节点执行状态</h4>
                        <div id="node-status-list-${execution.id}">加载中...</div>
                    </div>
                </div>
            </div>
        `).join('');
    }

    async handleFlowSubmission() {
        const form = document.getElementById('flow-form');
        const formData = new FormData(form);
        
        const flowData = {
            name: formData.get('name'),
            repo_url: formData.get('repo_url'),
            branch: formData.get('branch') || 'main',
            description: formData.get('description') || '',
            git_username: formData.get('git_username') || '',
            git_token: formData.get('git_token') || ''
        };

        try {
            const response = await this.apiCall('/flows', {
                method: 'POST',
                body: JSON.stringify(flowData)
            });

            // 处理新的API响应格式
            if (response.code === 0) {
                this.updateButlerMessage(`工作流 "${flowData.name}" 创建成功！`, 'success');
                this.closeModal();
                form.reset();
                this.loadFlows();
            } else {
                this.updateButlerMessage(`创建工作流失败: ${response.message || '未知错误'}`, 'error');
            }
        } catch (error) {
            this.updateButlerMessage(`创建工作流失败: ${error.message}`, 'error');
        }
    }

    /**
     * 处理节点表单提交
     */
    async handleNodeSubmission() {
        const form = document.getElementById('node-form');
        const formData = new FormData(form);
        
        const nodeData = {
            name: formData.get('name'),
            description: formData.get('description') || '',
            script_type: formData.get('script_type') || 'python',
            script_content: formData.get('script_content') || '',
            flow_id: this.currentFlowId
        };

        try {
            const response = await this.apiCall('/nodes', {
                method: 'POST',
                body: JSON.stringify(nodeData)
            });

            // 处理API响应格式
            if (response.code === 0) {
                this.updateButlerMessage(`节点 "${nodeData.name}" 创建成功！`, 'success');
                closeNodeModal();
                form.reset();
                // 重新加载当前工作流的节点
                if (this.currentFlowId) {
                    await this.loadFlowNodes(this.currentFlowId);
                }
            } else {
                this.updateButlerMessage(`创建节点失败: ${response.message || '未知错误'}`, 'error');
            }
        } catch (error) {
            this.updateButlerMessage(`创建节点失败: ${error.message}`, 'error');
        }
    }

    async executeFlow(flowId) {
        try {
            const response = await this.apiCall(`/flows/${flowId}/execute`, {
                method: 'POST'
            });

            // 处理新的API响应格式
            if (response.code === 0 && response.data && response.data.execution_id) {
                this.updateButlerMessage(`工作流执行已启动！执行ID: ${response.data.execution_id}`, 'success');
                this.loadExecutions();
            } else {
                this.updateButlerMessage(`执行工作流失败: ${response.message || '未知错误'}`, 'error');
            }
        } catch (error) {
            this.updateButlerMessage(`执行工作流失败: ${error.message}`, 'error');
        }
    }

    async deleteFlow(flowId) {
        if (!confirm('确定要删除这个工作流吗？')) {
            return;
        }

        try {
            const response = await this.apiCall(`/flows/${flowId}`, {
                method: 'DELETE'
            });

            // 处理新的API响应格式
            if (response.code === 0) {
                this.updateButlerMessage('工作流删除成功！', 'success');
                this.loadFlows();
            } else {
                this.updateButlerMessage(`删除工作流失败: ${response.message || '未知错误'}`, 'error');
            }
        } catch (error) {
            this.updateButlerMessage(`删除工作流失败: ${error.message}`, 'error');
        }
    }

    async showFlowDetails(flowId) {
        try {
            const response = await this.apiCall(`/flows/${flowId}`);
            // 处理新的API响应格式
            if (response.code === 0 && response.data) {
                const flow = response.data;
                this.currentFlowId = flowId;
                this.displayFlowDetailsModal(flow);
                await this.loadFlowNodes(flowId);
                this.updateButlerMessage(`正在查看工作流: ${flow.name}`);
            } else {
                this.updateButlerMessage(`获取工作流详情失败: ${response.message || '未知错误'}`, 'error');
            }
        } catch (error) {
            this.updateButlerMessage(`获取工作流详情失败: ${error.message}`, 'error');
        }
    }

    displayFlowDetailsModal(flow) {
        this.currentFlowId = flow.id;
        const modal = document.getElementById('flow-details-modal');
        const title = document.getElementById('flow-details-title');
        const flowInfo = document.getElementById('flow-info');
        
        if (title) {
            title.textContent = `工作流详情: ${flow.name}`;
        }
        
        if (flowInfo) {
            flowInfo.innerHTML = `
                <div class="info-item">
                    <label>名称:</label>
                    <input type="text" id="edit-flow-name" value="${this.escapeHtml(flow.name)}" style="width: 300px; padding: 5px; border: 1px solid #ddd; border-radius: 4px;">
                </div>
                <div class="info-item">
                    <label>描述:</label>
                    <textarea id="edit-flow-description" rows="3" style="width: 300px; padding: 5px; border: 1px solid #ddd; border-radius: 4px; resize: vertical;">${this.escapeHtml(flow.description || '')}</textarea>
                </div>
                <div class="info-item">
                    <label>仓库:</label>
                    <input type="url" id="edit-flow-repo" value="${this.escapeHtml(flow.repo_url || '')}" style="width: 400px; padding: 5px; border: 1px solid #ddd; border-radius: 4px;">
                </div>
                <div class="info-item">
                    <label>分支:</label>
                    <input type="text" id="edit-flow-branch" value="${this.escapeHtml(flow.branch || '')}" style="width: 200px; padding: 5px; border: 1px solid #ddd; border-radius: 4px;">
                </div>
                <div class="info-item">
                    <label>Git用户名:</label>
                    <input type="text" id="edit-flow-git-username" value="${this.escapeHtml(flow.git_username || '')}" style="width: 200px; padding: 5px; border: 1px solid #ddd; border-radius: 4px;" placeholder="用于私有仓库访问">
                </div>
                <div class="info-item">
                    <label>Git访问令牌:</label>
                    <input type="password" id="edit-flow-git-token" value="${this.escapeHtml(flow.git_token || '')}" style="width: 300px; padding: 5px; border: 1px solid #ddd; border-radius: 4px;" placeholder="Personal Access Token或密码">
                </div>
                <div class="info-item">
                    <label>创建时间:</label>
                    <span>${this.formatDate(flow.created_at)}</span>
                </div>
                <div class="info-item">
                    <button class="primary-btn" onclick="app.saveFlowInfo()" style="margin-right: 10px;">保存工作流信息</button>
                    <button class="secondary-btn" onclick="app.resetFlowInfo()" style="margin-right: 10px;">重置</button>
                </div>
            `;
        }
        
        // 保存原始数据用于重置
        this.originalFlowData = { ...flow };
        
        if (modal) {
            modal.style.display = 'flex';
        }
    }

    async loadFlowNodes(flowId) {
        try {
            const response = await this.apiCall(`/nodes?flow_id=${flowId}`);
            // 处理新的API响应格式
            if (response.code === 0 && response.data) {
                this.currentFlowNodes = Array.isArray(response.data) ? response.data : [response.data];
            } else {
                this.currentFlowNodes = [];
                if (response.message) {
                    this.updateButlerMessage(`加载工作流节点失败: ${response.message}`, 'error');
                }
            }
            this.renderFlowNodes();
        } catch (error) {
            this.updateButlerMessage(`加载工作流节点失败: ${error.message}`, 'error');
            this.currentFlowNodes = [];
            this.renderFlowNodes();
        }
    }

    renderFlowNodes() {
        const nodesList = document.getElementById('flow-nodes-list');
        if (!nodesList) return;

        if (this.currentFlowNodes.length === 0) {
            nodesList.innerHTML = '<div class="empty-state">该工作流暂无节点</div>';
            return;
        }

        nodesList.innerHTML = this.currentFlowNodes.map(node => `
            <div class="node-item">
                <div class="node-info">
                    <h5>${this.escapeHtml(node.name || 'Unnamed Node')}</h5>
                    <p>执行顺序: ${node.order || 0}</p>
                    ${node.description ? `<p>描述: ${this.escapeHtml(node.description)}</p>` : ''}
                </div>
                <div class="node-actions">
                    <button class="action-btn" onclick="app.showNodeDetails('${node.id}')">管理动作</button>
                    <button class="action-btn" onclick="app.editNode('${node.id}')">编辑</button>
                    <button class="action-btn danger" onclick="app.deleteNode('${node.id}')">删除</button>
                </div>
            </div>
        `).join('');
    }

    async updateFlow(flowId, flowData) {
        try {
            const response = await this.apiCall(`/flows/${flowId}`, {
                method: 'PUT',
                body: JSON.stringify(flowData)
            });
            
            // 处理新的API响应格式
            if (response.code === 0) {
                this.updateButlerMessage('工作流更新成功！', 'success');
                this.loadFlows();
                return response;
            } else {
                this.updateButlerMessage(`更新工作流失败: ${response.message || '未知错误'}`, 'error');
                throw new Error(response.message || '更新失败');
            }
        } catch (error) {
            this.updateButlerMessage(`更新工作流失败: ${error.message}`, 'error');
            throw error;
        }
    }

    async saveFlowInfo() {
        if (!this.currentFlowId) {
            this.updateButlerMessage('没有选中的工作流', 'error');
            return;
        }

        const nameInput = document.getElementById('edit-flow-name');
        const descriptionInput = document.getElementById('edit-flow-description');
        const repoInput = document.getElementById('edit-flow-repo');
        const branchInput = document.getElementById('edit-flow-branch');
        const gitUsernameInput = document.getElementById('edit-flow-git-username');
        const gitTokenInput = document.getElementById('edit-flow-git-token');
        
        if (!nameInput || !descriptionInput || !repoInput || !branchInput) {
            this.updateButlerMessage('找不到编辑字段', 'error');
            return;
        }

        const name = nameInput.value.trim();
        const repoUrl = repoInput.value.trim();
        
        if (!name) {
            this.updateButlerMessage('工作流名称不能为空', 'error');
            return;
        }
        
        if (!repoUrl) {
            this.updateButlerMessage('仓库地址不能为空', 'error');
            return;
        }

        try {
            const flowData = {
                name: name,
                description: descriptionInput.value.trim(),
                repo_url: repoUrl,
                branch: branchInput.value.trim() || 'main',
                git_username: gitUsernameInput ? gitUsernameInput.value.trim() : '',
                git_token: gitTokenInput ? gitTokenInput.value.trim() : ''
            };
            
            await this.updateFlow(this.currentFlowId, flowData);
            
            // 更新原始数据
            this.originalFlowData = { ...this.originalFlowData, ...flowData };
            
        } catch (error) {
            this.updateButlerMessage(`保存工作流信息失败: ${error.message}`, 'error');
        }
    }

    resetFlowInfo() {
        if (!this.originalFlowData) {
            this.updateButlerMessage('没有原始数据可重置', 'error');
            return;
        }

        const nameInput = document.getElementById('edit-flow-name');
        const descriptionInput = document.getElementById('edit-flow-description');
        const repoInput = document.getElementById('edit-flow-repo');
        const branchInput = document.getElementById('edit-flow-branch');
        const gitUsernameInput = document.getElementById('edit-flow-git-username');
        const gitTokenInput = document.getElementById('edit-flow-git-token');
        
        if (nameInput) nameInput.value = this.originalFlowData.name || '';
        if (descriptionInput) descriptionInput.value = this.originalFlowData.description || '';
        if (repoInput) repoInput.value = this.originalFlowData.repo_url || '';
        if (branchInput) branchInput.value = this.originalFlowData.branch || '';
        if (gitUsernameInput) gitUsernameInput.value = this.originalFlowData.git_username || '';
        if (gitTokenInput) gitTokenInput.value = this.originalFlowData.git_token || '';
        
        this.updateButlerMessage('已重置为原始数据', 'info');
    }

    async getFlowExecutions(flowId) {
        try {
            const response = await this.apiCall(`/flows/${flowId}/executions`);
            // Handle different response formats
            const executions = response.data || response;
            return Array.isArray(executions) ? executions : (executions ? [executions] : []);
        } catch (error) {
            this.updateButlerMessage(`获取工作流执行历史失败: ${error.message}`, 'error');
            return [];
        }
    }

    // Node Management Methods
    async loadNodes() {
        try {
            const response = await this.apiCall('/nodes');
            // Handle different response formats
            const nodes = response.data || response;
            this.nodes = Array.isArray(nodes) ? nodes : (nodes ? [nodes] : []);
            this.renderNodes();
        } catch (error) {
            this.updateButlerMessage(`加载节点失败: ${error.message}`, 'error');
            this.nodes = [];
        }
    }

    renderNodes() {
        const nodesList = document.getElementById('nodes-list');
        if (!nodesList) return;

        if (this.nodes.length === 0) {
            nodesList.innerHTML = '<div class="empty-state">暂无节点</div>';
            return;
        }

        nodesList.innerHTML = this.nodes.map(node => `
            <div class="build-item">
                <div class="build-info">
                    <h3>${this.escapeHtml(node.name || 'Unnamed Node')}</h3>
                    <p>类型: ${this.escapeHtml(node.type || 'Unknown')}</p>
                    <p>状态: ${node.enabled ? '启用' : '禁用'}</p>
                    ${node.description ? `<p>描述: ${this.escapeHtml(node.description)}</p>` : ''}
                </div>
                <div class="build-actions">
                    <button class="action-btn" onclick="app.showNodeDetails('${node.id}')">详情</button>
                    <button class="action-btn" onclick="app.editNode('${node.id}')">编辑</button>
                    <button class="action-btn danger" onclick="app.deleteNode('${node.id}')">删除</button>
                </div>
            </div>
        `).join('');
    }

    async createNode(nodeData) {
        try {
            const response = await this.apiCall('/nodes', {
                method: 'POST',
                body: JSON.stringify(nodeData)
            });
            this.updateButlerMessage('节点创建成功！', 'success');
            this.loadNodes();
            return response;
        } catch (error) {
            this.updateButlerMessage(`创建节点失败: ${error.message}`, 'error');
            throw error;
        }
    }

    async updateNode(nodeId, nodeData) {
        try {
            const response = await this.apiCall(`/nodes/${nodeId}`, {
                method: 'PUT',
                body: JSON.stringify(nodeData)
            });
            this.updateButlerMessage('节点更新成功！', 'success');
            this.loadNodes();
            return response;
        } catch (error) {
            this.updateButlerMessage(`更新节点失败: ${error.message}`, 'error');
            throw error;
        }
    }

    async deleteNode(nodeId) {
        if (!confirm('确定要删除这个节点吗？')) {
            return;
        }

        try {
            const response = await this.apiCall(`/nodes/${nodeId}`, {
                method: 'DELETE'
            });
            
            // 处理新的API响应格式
            if (response.code === 0) {
                this.updateButlerMessage('节点删除成功！', 'success');
                // 刷新当前工作流的节点列表
                if (this.currentFlowId) {
                    await this.loadFlowNodes(this.currentFlowId);
                }
                // 关闭节点详情模态框
                const modal = document.getElementById('node-details-modal');
                if (modal) {
                    modal.style.display = 'none';
                }
            } else {
                this.updateButlerMessage(`删除节点失败: ${response.message || '未知错误'}`, 'error');
            }
        } catch (error) {
            this.updateButlerMessage(`删除节点失败: ${error.message}`, 'error');
        }
    }

    async showNodeDetails(nodeId) {
        try {
            const response = await this.apiCall(`/nodes/${nodeId}`);
            const node = response.data || response;
            
            if (node && node.name) {
                this.currentNodeId = nodeId;
                this.displayNodeDetailsModal(node);
                await this.loadNodeScript(nodeId);
                this.updateButlerMessage(`正在查看节点: ${node.name}`);
            } else {
                this.updateButlerMessage('节点详情格式错误', 'error');
            }
        } catch (error) {
            this.updateButlerMessage(`获取节点详情失败: ${error.message}`, 'error');
        }
    }

    displayNodeDetailsModal(node) {
        const modal = document.getElementById('node-details-modal');
        const title = document.getElementById('node-details-title');
        const nodeInfo = document.getElementById('node-info');
        
        if (title) {
            title.textContent = `节点详情: ${node.name}`;
        }
        
        if (nodeInfo) {
            nodeInfo.innerHTML = `
                <div class="info-item">
                    <label>名称:</label>
                    <span>${this.escapeHtml(node.name)}</span>
                </div>
                <div class="info-item">
                    <label>描述:</label>
                    <span>${this.escapeHtml(node.description || '无描述')}</span>
                </div>
                <div class="info-item">
                    <label>执行顺序:</label>
                    <span>${node.order || 0}</span>
                </div>
                <div class="info-item">
                    <label>创建时间:</label>
                    <span>${this.formatDate(node.created_at)}</span>
                </div>
            `;
        }
        
        if (modal) {
            modal.style.display = 'flex';
        }
    }

    async loadNodeScript(nodeId) {
        try {
            const response = await this.apiCall(`/nodes/${nodeId}/script`);
            const script = response.data || response;
            if (script) {
                document.getElementById('script-type').value = script.type || 'python';
                document.getElementById('script-content').value = script.content || '';
                this.updateButlerMessage(`已加载节点脚本`);
            } else {
                // 清空脚本编辑器
                document.getElementById('script-type').value = 'python';
                document.getElementById('script-content').value = '';
            }
        } catch (error) {
            this.updateButlerMessage(`加载节点脚本失败: ${error.message}`, 'error');
            // 清空脚本编辑器
            document.getElementById('script-type').value = 'python';
            document.getElementById('script-content').value = '';
        }
    }

    async saveNodeScript() {
        if (!this.currentNodeId) {
            this.updateButlerMessage('请先选择一个节点', 'error');
            return;
        }

        const scriptType = document.getElementById('script-type').value;
        const scriptContent = document.getElementById('script-content').value;

        if (!scriptContent.trim()) {
            this.updateButlerMessage('请输入脚本内容', 'error');
            return;
        }

        try {
            const scriptData = {
                type: scriptType,
                content: scriptContent,
                node_id: this.currentNodeId
            };

            await this.apiCall(`/nodes/${this.currentNodeId}/script`, {
                method: 'POST',
                body: JSON.stringify(scriptData)
            });
            
            this.updateButlerMessage('脚本保存成功！', 'success');
        } catch (error) {
            this.updateButlerMessage(`保存脚本失败: ${error.message}`, 'error');
        }
    }

    async saveNodeInfo() {
        if (!this.currentNodeId) {
            this.updateButlerMessage('没有选中的节点', 'error');
            return;
        }

        const nameInput = document.getElementById('edit-node-name');
        const descriptionInput = document.getElementById('edit-node-description');
        const orderInput = document.getElementById('edit-node-order');
        
        if (!nameInput || !descriptionInput || !orderInput) {
            this.updateButlerMessage('找不到编辑字段', 'error');
            return;
        }

        const name = nameInput.value.trim();
        if (!name) {
            this.updateButlerMessage('节点名称不能为空', 'error');
            return;
        }

        try {
            const response = await this.apiCall(`/nodes/${this.currentNodeId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    name: name,
                    description: descriptionInput.value.trim(),
                    order: parseInt(orderInput.value) || 0
                })
            });
            
            // 处理新的API响应格式
            if (response.code === 0) {
                this.updateButlerMessage('节点信息保存成功！', 'success');
                // 刷新节点列表
                if (this.currentFlowId) {
                    await this.loadFlowNodes(this.currentFlowId);
                }
            } else {
                this.updateButlerMessage(`保存节点信息失败: ${response.message || '未知错误'}`, 'error');
            }
        } catch (error) {
            this.updateButlerMessage(`保存节点信息失败: ${error.message}`, 'error');
        }
    }

    onScriptTypeChange() {
        const scriptType = document.getElementById('script-type').value;
        const textarea = document.getElementById('script-content');
        
        // 根据脚本类型设置占位符
        if (scriptType === 'python') {
            textarea.placeholder = '请输入Python3脚本代码...\n\n示例:\nprint("Hello, World!")\nimport os\nprint(os.getcwd())';
        } else if (scriptType === 'shell') {
            textarea.placeholder = '请输入Shell脚本代码...\n\n示例:\n#!/bin/bash\necho "Hello, World!"\npwd';
        }
        
        this.updateButlerMessage(`已切换到${scriptType === 'python' ? 'Python3' : 'Shell'}脚本模式`);
    }

    // Script Management Methods for Node Details

    // 移除了原有的动作管理方法，改为脚本管理

    // 已移除 createNodeAction 方法，改为使用脚本管理

    // Node creation for Flow Details
    async createFlowNode() {
        if (!this.currentFlowId) {
            this.updateButlerMessage('请先选择一个工作流', 'error');
            return;
        }
        
        // Create node creation modal
        const modal = document.createElement('div');
        modal.className = 'modal';
        modal.style.display = 'flex';
        modal.innerHTML = `
            <div class="modal-content">
                <div class="modal-header">
                    <h3>创建新节点</h3>
                    <span class="close" onclick="this.parentElement.parentElement.parentElement.remove()">&times;</span>
                </div>
                <div class="modal-body">
                    <form id="create-node-form">
                        <div class="form-group">
                            <label for="new-node-name">节点名称:</label>
                            <input type="text" id="new-node-name" required>
                        </div>
                        <div class="form-group">
                            <label for="new-node-description">节点描述:</label>
                            <textarea id="new-node-description" rows="3" placeholder="请输入节点描述..."></textarea>
                        </div>
                        <div class="form-group">
                            <label for="new-node-order">执行顺序:</label>
                            <input type="number" id="new-node-order" value="0" min="0">
                        </div>
                        <div class="form-actions">
                            <button type="button" onclick="this.closest('.modal').remove()">取消</button>
                            <button type="submit">创建</button>
                        </div>
                    </form>
                </div>
            </div>
        `;
        document.body.appendChild(modal);
        
        // Handle form submission
        const form = modal.querySelector('#create-node-form');
        form.addEventListener('submit', async (e) => {
            e.preventDefault();
            const formData = {
                name: document.getElementById('new-node-name').value,
                description: document.getElementById('new-node-description').value,
                order: parseInt(document.getElementById('new-node-order').value) || 0,
                flow_id: this.currentFlowId
            };
            
            try {
                 await this.apiCall('/nodes', {
                     method: 'POST',
                     body: JSON.stringify(formData)
                 });
                 this.updateButlerMessage('节点创建成功');
                 await this.loadFlowNodes(this.currentFlowId);
                 modal.remove();
             } catch (error) {
                 this.updateButlerMessage(`创建节点失败: ${error.message}`, 'error');
             }
        });
    }

    async loadExecutionNodeStatus(executionId) {
        try {
            // 模拟获取节点执行状态的API调用
            // 实际应该调用后端API获取节点状态
            const response = await this.apiCall(`/executions/${executionId}/nodes`);
            const nodeStatuses = response.data || [];
            
            const nodeStatusContainer = document.getElementById(`node-status-list-${executionId}`);
            if (nodeStatusContainer) {
                if (nodeStatuses.length === 0) {
                    nodeStatusContainer.innerHTML = '<div class="empty-state">暂无节点状态信息</div>';
                    return;
                }
                
                nodeStatusContainer.innerHTML = nodeStatuses.map(node => `
                    <div class="node-execution-item ${node.status}">
                        <div class="node-status-indicator ${node.status}"></div>
                        <div class="node-execution-info">
                            <h5>${this.escapeHtml(node.node_name || node.name || 'Unknown Node')}</h5>
                            <p>状态: ${this.getNodeStatusText(node.status)}</p>
                            ${node.started_at ? `<p>开始: ${this.formatDate(node.started_at)}</p>` : ''}
                            ${node.finished_at ? `<p>结束: ${this.formatDate(node.finished_at)}</p>` : ''}
                            <button class="view-script-btn" onclick="app.viewNodeScript('${node.id}', '${this.escapeHtml(node.node_name || node.name || 'Unknown Node')}')">查看脚本</button>
                        </div>
                        ${node.error ? `<div class="node-error-message">${this.escapeHtml(node.error)}</div>` : ''}
                        ${node.output ? `<div class="node-output"><strong>输出:</strong> <pre>${this.escapeHtml(node.output)}</pre></div>` : ''}
                    </div>
                `).join('');
            }
        } catch (error) {
            const nodeStatusContainer = document.getElementById(`node-status-list-${executionId}`);
            if (nodeStatusContainer) {
                nodeStatusContainer.innerHTML = '<div class="empty-state">加载节点状态失败</div>';
            }
        }
    }

    calculateExecutionProgress(execution) {
        // 根据执行状态计算进度百分比
        switch (execution.status) {
            case 'pending':
                return 0;
            case 'running':
                return 50; // 可以根据实际节点完成情况动态计算
            case 'success':
                return 100;
            case 'failed':
                return 100; // 失败也算完成
            default:
                return 0;
        }
    }

    getNodeStatusText(status) {
        const statusMap = {
            'pending': '等待中',
            'running': '运行中',
            'success': '成功',
            'failed': '失败'
        };
        return statusMap[status] || status;
    }

    async showExecutionDetails(executionId) {
        try {
            const detailsDiv = document.getElementById(`execution-details-${executionId}`);
            if (detailsDiv) {
                if (detailsDiv.style.display === 'none') {
                    detailsDiv.style.display = 'block';
                    await this.loadExecutionNodeStatus(executionId);
                } else {
                    detailsDiv.style.display = 'none';
                }
            }
            
            const response = await this.apiCall(`/executions/${executionId}`);
            const execution = response.data || response;
            
            if (execution && execution.id) {
                let message = `执行详情 #${execution.id}: ${this.getStatusText(execution.status)}`;
                if (execution.error) {
                    message += ` - 错误: ${execution.error}`;
                }
                this.updateButlerMessage(message);
            } else {
                this.updateButlerMessage('执行详情格式错误', 'error');
            }
        } catch (error) {
            this.updateButlerMessage(`获取执行详情失败: ${error.message}`, 'error');
        }
    }

    /**
     * 查看节点脚本内容
     * @param {string} nodeId - 节点ID
     * @param {string} nodeName - 节点名称
     */
    async viewNodeScript(nodeId, nodeName) {
        try {
            const response = await this.apiCall(`/nodes/${nodeId}`);
            const node = response.data || response;
            
            if (node && node.id) {
                this.showScriptModal(node, nodeName);
            } else {
                this.updateButlerMessage('获取节点信息失败', 'error');
            }
        } catch (error) {
            this.updateButlerMessage(`获取节点脚本失败: ${error.message}`, 'error');
        }
    }

    /**
     * 显示脚本查看模态框
     * @param {Object} node - 节点对象
     * @param {string} nodeName - 节点名称
     */
    showScriptModal(node, nodeName) {
        // 创建模态框HTML
        const modalHtml = `
            <div id="script-view-modal" class="modal" style="display: flex;">
                <div class="modal-content large">
                    <div class="modal-header">
                        <h3>节点脚本: ${this.escapeHtml(nodeName)}</h3>
                        <button type="button" class="close-btn" onclick="app.closeScriptModal()">&times;</button>
                    </div>
                    <div class="modal-body">
                        <div class="script-info">
                            <p><strong>节点名称:</strong> ${this.escapeHtml(node.name || nodeName)}</p>
                            <p><strong>脚本类型:</strong> ${this.escapeHtml(node.script_type || 'unknown')}</p>
                        </div>
                        <div class="script-content-view">
                            <h4>脚本内容:</h4>
                            <pre class="script-code"><code>${this.escapeHtml(node.script_content || '暂无脚本内容')}</code></pre>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        // 移除已存在的模态框
        const existingModal = document.getElementById('script-view-modal');
        if (existingModal) {
            existingModal.remove();
        }
        
        // 添加新模态框到页面
        document.body.insertAdjacentHTML('beforeend', modalHtml);
    }

    /**
     * 关闭脚本查看模态框
     */
    closeScriptModal() {
        const modal = document.getElementById('script-view-modal');
        if (modal) {
            modal.remove();
        }
    }

    /**
     * 编辑节点
     * @param {string} nodeId - 节点ID
     */
    async editNode(nodeId) {
        try {
            const response = await this.apiCall(`/nodes/${nodeId}`);
            const node = response.data || response;
            
            if (node && node.id) {
                this.currentNodeId = nodeId;
                this.showNodeDetailsModal(node);
                this.updateButlerMessage(`正在编辑节点: ${node.name}`);
            } else {
                this.updateButlerMessage('获取节点信息失败', 'error');
            }
        } catch (error) {
            this.updateButlerMessage(`获取节点信息失败: ${error.message}`, 'error');
        }
    }

    /**
     * 显示节点详情模态框
     * @param {Object} node - 节点对象
     */
    showNodeDetailsModal(node) {
        const modal = document.getElementById('node-details-modal');
        const title = document.getElementById('node-details-title');
        const nodeInfo = document.getElementById('node-info');
        const scriptContent = document.getElementById('script-content');
        const scriptType = document.getElementById('script-type');
        
        if (title) {
            title.textContent = `节点详情: ${node.name}`;
        }
        
        if (nodeInfo) {
            nodeInfo.innerHTML = `
                <div class="info-item">
                    <label>名称:</label>
                    <input type="text" id="edit-node-name" value="${this.escapeHtml(node.name)}" style="width: 300px; padding: 5px; border: 1px solid #ddd; border-radius: 4px;">
                </div>
                <div class="info-item">
                    <label>描述:</label>
                    <textarea id="edit-node-description" rows="3" style="width: 300px; padding: 5px; border: 1px solid #ddd; border-radius: 4px; resize: vertical;">${this.escapeHtml(node.description || '')}</textarea>
                </div>
                <div class="info-item">
                    <label>执行顺序:</label>
                    <input type="number" id="edit-node-order" value="${node.order || 0}" style="width: 100px; padding: 5px; border: 1px solid #ddd; border-radius: 4px;">
                </div>
                <div class="info-item">
                    <label>创建时间:</label>
                    <span>${this.formatDate(node.created_at)}</span>
                </div>
                <div class="info-item">
                    <button class="primary-btn" onclick="app.saveNodeInfo()">保存节点信息</button>
                </div>
            `;
        }
        
        if (scriptContent) {
            scriptContent.value = node.script_content || '';
        }
        
        if (scriptType) {
            scriptType.value = node.script_type || 'python';
        }
        
        if (modal) {
            modal.style.display = 'flex';
        }
    }

    updateButlerMessage(message, type = 'info') {
        const butlerText = document.getElementById('butler-text');
        if (butlerText) {
            butlerText.textContent = message;
            
            // Add visual feedback based on message type
            const messageContent = butlerText.parentElement;
            messageContent.className = `message-content ${type}`;
            
            // Auto-clear error/success messages after 5 seconds
            if (type === 'error' || type === 'success') {
                setTimeout(() => {
                    if (butlerText.textContent === message) {
                        this.updateButlerMessage('Alfred 已准备就绪，随时为您服务！');
                    }
                }, 5000);
            }
        }
    }

    getStatusText(status) {
        const statusMap = {
            'pending': '等待中',
            'running': '运行中',
            'success': '成功',
            'failed': '失败',
            'cancelled': '已取消'
        };
        return statusMap[status] || status;
    }

    formatDate(dateString) {
        if (!dateString) return 'N/A';
        const date = new Date(dateString);
        return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        });
    }

    escapeHtml(text) {
        if (!text) return '';
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    // Modal functions
    openModal() {
        const modal = document.getElementById('flow-modal');
        if (modal) {
            modal.style.display = 'flex';
        }
    }

    closeModal() {
        const modal = document.getElementById('flow-modal');
        if (modal) {
            modal.style.display = 'none';
        }
    }
}

// Global functions for HTML onclick handlers
function createFlow() {
    app.openModal();
}

function closeModal() {
    app.closeModal();
}

function refreshFlows() {
    app.loadFlows();
    app.updateButlerMessage('工作流列表已刷新');
}

function refreshExecutions() {
    app.loadExecutions();
    app.updateButlerMessage('执行历史已刷新');
}

function createNode() {
    if (app.currentFlowId) {
        app.createFlowNode();
    } else {
        app.updateButlerMessage('请先选择一个工作流', 'error');
    }
}

function createAction() {
    if (app.currentNodeId) {
        app.updateButlerMessage('请在节点详情中直接编辑脚本代码', 'info');
    } else {
        app.updateButlerMessage('请先选择一个节点', 'error');
    }
}

function closeFlowDetailsModal() {
    const modal = document.getElementById('flow-details-modal');
    if (modal) {
        modal.style.display = 'none';
    }
}

function closeNodeDetailsModal() {
    const modal = document.getElementById('node-details-modal');
    if (modal) {
        modal.style.display = 'none';
    }
}

function createNodeForFlow() {
    if (!app.currentFlowId) {
        app.updateButlerMessage('请先选择一个工作流', 'error');
        return;
    }
    
    // 打开节点创建模态框
    const modal = document.getElementById('node-modal');
    if (modal) {
        modal.style.display = 'flex';
        // 重置表单
        const form = document.getElementById('node-form');
        if (form) {
            form.reset();
        }
    }
}

function closeNodeModal() {
    const modal = document.getElementById('node-modal');
    if (modal) {
        modal.style.display = 'none';
    }
}

/**
 * 切换标签页显示
 * @param {string} tabName - 标签页名称 ('flows' 或 'executions')
 */
function switchTab(tabName) {
    // 移除所有标签按钮的active类
    document.querySelectorAll('.tab-btn').forEach(btn => {
        btn.classList.remove('active');
    });
    
    // 隐藏所有面板
    document.querySelectorAll('.panel-fullwidth').forEach(panel => {
        panel.classList.remove('active');
    });
    
    // 激活当前标签按钮
    event.target.classList.add('active');
    
    // 显示对应面板
    const targetPanel = document.getElementById(`${tabName}-panel`);
    if (targetPanel) {
        targetPanel.classList.add('active');
    }
    
    // 更新Butler消息和加载对应数据
    const messages = {
        'flows': 'Alfred 正在为您展示工作流管理界面',
        'executions': 'Alfred 正在为您展示执行历史记录'
    };
    
    if (app && messages[tabName]) {
        app.updateButlerMessage(messages[tabName]);
        
        // 根据标签页加载对应数据
        switch(tabName) {
            case 'flows':
                app.loadFlows();
                break;
            case 'executions':
                app.loadExecutions();
                break;
        }
    }
}

// Initialize the application when DOM is loaded
let app;
document.addEventListener('DOMContentLoaded', function() {
    app = new AlfredApp();
    window.app = app;
});